#include <iostream>
using std::cout;
using std::endl;
//验证虚表的存在
class Base{

virtual
  void print(){
      cout << "Base::print()" << endl;
  }

virtual
  void display(){
      cout << "Base::display()" << endl;
  }

virtual
  void show(){
      cout << "Base::show()" << endl;
  }

private:
long _base = 10;
};

class Derived
: public Base
{

  void print(){
      cout << "Derived::print()" << endl;
  }

  void display(){
      cout << "Derived::display()" << endl;
  }

  void show(){
      cout << "Derived::show()" << endl;
  }

private:
long _derived = 100;
};

void test(){
    //创建派生类对象
    Derived d;
    Derived * pd = &d;
    //上述指针可以操作的内存大小是24字节
    //将上述的指针强转为long*指针
    //此时plong就等于途中所示的vfptr
    long * vfptr = (long *)pd;
    //此时显示的是_base的值
    cout << *(vfptr + 1) << endl;
    //此时显示的是_derived的值
    cout << *(vfptr + 2) << endl;

    //此时vtable其实就是虚表里面存储的虚函数的地址值
    long * vtable = (long *)*vfptr;

    //定义一个函数指针
    typedef void (*FunctionPointer)(void);
    //下面的这三种写法是在运算符重载这一章节新引入的一种方式
    FunctionPointer fp;
    FunctionPointer fp2;
    FunctionPointer fp3;

    //Derived::print;
    fp = (FunctionPointer)*vtable;
    //Derived::display() 
    fp2 = (FunctionPointer)*(vtable + 1);
    //Derived::show()
    fp3 = (FunctionPointer)*(vtable + 2);
    fp();
    fp2();
    fp3();
}

int main()
{
    test();
    return 0;
}

